package com.globaldom.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.globaldom.model.CivResource;
import com.globaldom.model.CountryDetail;
import com.globaldom.model.MilResource;
import com.globaldom.model.Person;
import com.globaldom.model.PersonLocation;
import com.globaldom.utils.Constants;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.appengine.api.labs.taskqueue.TaskOptions.Method;

@Controller
@RequestMapping(value = "/resource")
public class ResourceController {
	public ResourceController() {
	}
	private static final Logger log = Logger.getLogger(ResourceController.class.getName());
	// initializing method
	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(HttpServletRequest request, Model model, HttpSession session) {

		if (null != request.getParameter("l")) {
			Constants.local = true;
			initLocal(session);
		} else {
			Constants.local = false;
		}
		String personID = SessionManager.getID(request, session);
		if(null==personID) return "loggedout";

		
		Queue queue = QueueFactory.getDefaultQueue();
		TaskOptions taskOptions = TaskOptions.Builder.url("/getallcivs/asynkgetallcivresources").param("personID",
				personID.toString());
		taskOptions.method(Method.GET);
		queue.add(taskOptions);

		// initLocal() ;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Person person = pm.getObjectById(Person.class, personID);

			Query query = pm.newQuery(PersonLocation.class, "locationType==0 && person==pid");
			query.declareParameters("String pid");
			PersonLocation homeLocation = (PersonLocation) ((List<PersonLocation>) query.execute(personID)).get(0);

			query = pm.newQuery(CivResource.class, "person==pid");
			query.declareParameters("String pid");
			List<CivResource> civlist = (List<CivResource>) query.execute(personID);

			query = pm.newQuery(MilResource.class, "person==pid");
			query.declareParameters("String pid");
			List<MilResource> millist = (List<MilResource>) query.execute(personID);
			pm.detachCopyAll(civlist);
			pm.detachCopyAll(millist);
			model.addAttribute("civresource", civlist);
			model.addAttribute("milresource", millist);

			model.addAttribute("homeLat", homeLocation.getLatitude());
			model.addAttribute("homeLon", homeLocation.getLongitude());
			model.addAttribute("level", person.getLevel());
			int ccode = person.getCountryCode();
			model.addAttribute("homeCountry", ccode);
			model.addAttribute("enemyCountry", "PK");
			model.addAttribute("totalRes", person.getMaxCivilians());
			model.addAttribute("fbtoken", session.getAttribute("fbtoken"));

		} catch (Exception ex) {
			log.severe("Exception! while in resource controller " + ex.getMessage() + " ." + ex);
			return "redirect:/" + Constants.mainpage;

		} finally {
			pm.close();
		}

		return "start";
	}

	// ----------------internal helpers
	// ------------ experimental features

	private void initLocal(HttpSession session) {
		Constants.PERSONID = new Integer( (int) Math.floor(Math.random() * 10000 * 14)).toString();

		PersistenceManager pm = PMF.get().getPersistenceManager();
		session.setAttribute("personID", Constants.PERSONID);

		

		List<CountryDetail> list = null;
		// list = MemCacheManager.getAllCountries();
		// if (null == list) {
		list = new ArrayList<CountryDetail>();
		CountryDetail cdx = new CountryDetail();
		cdx.setCflag("india.png");
		cdx.setCCode("IN");
		cdx.setCName("India");
		list.add(cdx);
		CountryDetail cd = new CountryDetail();
		cd.setCflag("us.png");
		cd.setCCode("US");
		cd.setCName("USA");
		list.add(cd);
		CountryDetail cd1 = new CountryDetail();
		cd1.setCflag("china.png");
		cd1.setCCode("CN");
		cd1.setCName("China");
		list.add(cd1);
		CountryDetail cd2 = new CountryDetail();
		cd2.setCflag("france.png");
		cd2.setCCode("FR");
		cd2.setCName("France");
		list.add(cd2);
		pm.makePersistentAll(list);
		pm.close();
		// MemCacheManager.putCountries(list);
		// }

		int countryCode = cdx.getId().intValue();


		
		
		try {
			PersistenceManager pmperson= PMF.get().getPersistenceManager();
			Person person = new Person();
			person.setId(Constants.PERSONID);
			person.setFirstName("Alfa");
			person.setLastName("Male");
			person.setKarma(0);
			person.setLevel(1);
			person.setPowerLevel(100);
			person.setCountryCode(countryCode);
			pmperson.makePersistent(person);
			pmperson.close();
			
			List<CivResource> allres = new ArrayList<CivResource>();
			CivResource resFood = new CivResource();
			resFood.setId(Constants.PERSONID + "/"+ CivResource.FOOD);
			resFood.setResType(CivResource.FOOD);
			resFood.setCivDeployed(6);
			resFood.setResAvailable(6000L);
			resFood.setResourceUpdated(new Date());
			resFood.setPerson(Constants.PERSONID);
			allres.add(resFood);
			
			CivResource resWater = new CivResource();
			resWater.setId(Constants.PERSONID + "/"+ CivResource.WATER);
			resWater.setResType(CivResource.WATER);
			resWater.setCivDeployed(5);
			resWater.setResAvailable(5000L);
			resWater.setResourceUpdated(new Date());
			resWater.setPerson(Constants.PERSONID);
			allres.add(resWater);
			CivResource resOil = new CivResource();
			resOil.setId(Constants.PERSONID + "/"+ CivResource.OIL);
			resOil.setResType(CivResource.OIL);
			resOil.setCivDeployed(4);
			resOil.setResAvailable(4000l);
			resOil.setPerson(Constants.PERSONID);
			allres.add(resOil);
			CivResource resWood = new CivResource();
			resWood.setId(Constants.PERSONID + "/"+ CivResource.WOOD);
			resWood.setResType(CivResource.WOOD);
			resWood.setCivDeployed(3);
			resWood.setResAvailable(3000L);
			resWood.setPerson(Constants.PERSONID);
			allres.add(resWood);
			CivResource resSilver = new CivResource();
			resSilver.setId(Constants.PERSONID + "/"+ CivResource.SILVER);
			resSilver.setResType(CivResource.SILVER);
			resSilver.setCivDeployed(2);
			resSilver.setResAvailable(2000L);
			resSilver.setPerson(Constants.PERSONID);
			allres.add(resSilver);

			CivResource resGold = new CivResource();
			resGold.setId(Constants.PERSONID + "/"+ CivResource.GOLD);
			resGold.setResType(CivResource.GOLD);
			resGold.setCivDeployed(1);
			resGold.setResAvailable(1000L);
			resGold.setPerson(Constants.PERSONID);
			allres.add(resGold);
			CivResource resDollar = new CivResource();
			resDollar.setId(Constants.PERSONID + "/"+ CivResource.DOLLAR);
			resDollar.setResType(CivResource.DOLLAR);
			resDollar.setCivDeployed(0);
			resDollar.setResAvailable(1000L);
			resDollar.setPerson(Constants.PERSONID);
			allres.add(resDollar);

			CivResource resKarma = new CivResource();
			resKarma.setId(Constants.PERSONID + "/"+ CivResource.KARMA);
			resKarma.setResType(CivResource.KARMA);
			resKarma.setCivDeployed(0);
			resKarma.setResAvailable(2500L);
			resKarma.setPerson(Constants.PERSONID);
			allres.add(resKarma);

			CivResource resXP = new CivResource();
			resXP.setId(Constants.PERSONID + "/"+ CivResource.XP);
			resXP.setResType(CivResource.XP);
			resXP.setCivDeployed(0);
			resXP.setResAvailable(2000L);
			resXP.setPerson(Constants.PERSONID);
			allres.add(resXP);
			PersistenceManager pmciv= PMF.get().getPersistenceManager();
			pmciv.makePersistentAll(allres);
			pmciv.close();
			
			List<MilResource> milres = new ArrayList<MilResource>();
			MilResource milArmy = new MilResource();
			milArmy.setId(Constants.PERSONID + "/"+ MilResource.ARMY);
			milArmy.setUnitType(MilResource.ARMY);
			milArmy.setMilAvailable(600l);
			milArmy.setResourceUpdated(new Date());
			milArmy.setPerson(Constants.PERSONID);
			milres.add(milArmy);

			MilResource milTank = new MilResource();
			milTank.setId(Constants.PERSONID + "/"+ MilResource.TANK);
			milTank.setUnitType(MilResource.TANK);
			milTank.setMilAvailable(500l);
			milTank.setResourceUpdated(new Date());
			milTank.setPerson(Constants.PERSONID);
			milres.add(milTank);

			MilResource milAir = new MilResource();
			milAir.setId(Constants.PERSONID + "/"+ MilResource.AIR);
			milAir.setUnitType(MilResource.AIR);
			milAir.setMilAvailable(400l);
			milAir.setPerson(Constants.PERSONID);
			milAir.setResourceUpdated(new Date());
			milres.add(milAir);

			MilResource milNavy = new MilResource();
			milNavy.setId(Constants.PERSONID + "/"+ MilResource.NAVY);
			milNavy.setUnitType(MilResource.NAVY);
			milNavy.setMilAvailable(300l);
			milNavy.setPerson(Constants.PERSONID);
			milNavy.setResourceUpdated(new Date());
			milres.add(milNavy);

			MilResource milSpies = new MilResource();
			milSpies.setId(Constants.PERSONID + "/"+ MilResource.SPIES);
			milSpies.setUnitType(MilResource.SPIES);
			milSpies.setPerson(Constants.PERSONID);
			milSpies.setMilAvailable(200l);
			milSpies.setResourceUpdated(new Date());
			milres.add(milSpies);

			MilResource milSubs = new MilResource();
			milSubs.setId(Constants.PERSONID + "/"+ MilResource.SUB);
			milSubs.setUnitType(MilResource.SUB);
			milSubs.setPerson(Constants.PERSONID);
			milSubs.setMilAvailable(100l);
			milSubs.setResourceUpdated(new Date());
			milres.add(milSubs);
			PersistenceManager pmmil= PMF.get().getPersistenceManager();
			pmmil.makePersistentAll(milres);
			pmmil.close();
			

			
			PersonLocation pl = new PersonLocation();
			pl.setLocationType(Constants.LocationType.HOME.ordinal());
			pl.setLatitude(28.448730F);
			pl.setLongitude(77.211914F);
			pl.setDateCreated(new Date());
			pl.setPerson(Constants.PERSONID);
			PersistenceManager pmloc= PMF.get().getPersistenceManager();
			pmloc.makePersistent(pl);
			pmloc.close();

		} finally {
			
		}

	}

}
